<?php

use Biz\model\advertisement\MUserprofileLabels;

ini_set('memory_limit', '2048M');
ini_set('display_errors', 1);
require_once '/data/wwwroot/g_vendor/autoload.php';

$day = $argv[1] ?? date('Ymd', strtotime('-1 day')); //20211222
$count = $argv[2] ?? 0;
$t = \Biz\service\advertisement\STimeRecorder::getInstance();
if ($day) {
    $where = ['day' => $day, 'OR' => ['note_video_count[>]'=> 0, 'note_pic_count[>]' => 0]];
    $uids = \Biz\model\bigData\MUserProfileNoteDrafts::select('uid', $where);
    $t->record('bigdata');
    if (empty($uids)) exit('no uids');
    $uids = array_combine($uids, $uids);
    //查找所有存在的数据
    $all = MUserprofileLabels::all();
    $t->record('exists');
    $label = 'drafts';
    $modify = [];
    foreach ($all as $v) {
        $eUid = $v['uid'];
        $labels = $v['labels'] ? explode(',', $v['labels']) : [];
        $labels = array_combine($labels, $labels);
        if (isset($uids[$eUid])) {
            // 如果没有标识, 新增标识
            if (!in_array($label, $labels)) {
                $labels[$label] = $label;
                sort($labels);
                $modify[$v['id']] = ['labels' => implode(',', $labels)];
                $create[$eUid] = [$label => 1];
            }
            unset($uids[$eUid]);
        } else {
            // 去掉标识
            unset($labels[$label]);
            sort($labels);
            $temp = implode(',', $labels);
            if ($v['labels'] == $temp) continue;
            $modify[$v['id']] = ['labels' => $temp];
            $delete[$eUid] = [$label];
        }
    }
    unset($all);
    $t->record('query');
    // 新增
    $create= [];
    foreach ($uids as $uid) {
        MUserprofileLabels::create(['uid' => $uid, 'labels' => $label]);
        $create[$uid] = [$label => 1];
    }
    $t->record('create:' . count($create));
    // 修改
    foreach ($modify as $id => $v) {
        MUserprofileLabels::modify($id, $v);
    }
    $t->record('save:' . count($modify));
    // redis 新增任务
    if (!empty($create)) \Biz\cache\advertisement\CUserLabels::setMulti($create);
    $t->record('redis create');
    // redis 删除任务
    if (!empty($delete)) \Biz\cache\advertisement\CUserLabels::delMulti($delete);
    $t->record('redis delete');

    echo $t;
}

